import type { ConfirmOptions, MsgBoxOptions } from './types'
import { createModal } from '../modal'
import MsgBox from './MsgBox.vue'
import type { MessageType } from '../../message/types'

export function showMsgBox(opts: MsgBoxOptions, type?: MessageType) {
  const negative = !(!opts.negativeText && !opts.onNegative)
  const positiveText = opts.positiveText || '确认'
  const negativeText = negative ? opts.negativeText || '取消' : undefined
  const events: { [event: string]: (...args: any) => any } = {}
  if (opts.onPositive) {
    events.positive = opts.onPositive
  }
  if (opts.onNegative) {
    events.negative = opts.onNegative
  }
  createModal({
    component: MsgBox,
    closeOnBackgroundClicked: false,
    showCloseButton: false,
    props: {
      type: type,
      title: opts.title,
      content: opts.content || opts.contentHtml || '',
      contentHtml: !opts.content,
      positiveText,
      negativeText
    },
    events
  })
}

export function showConfirm(opts: ConfirmOptions): Promise<boolean> {
  return new Promise((resolve) => {
    showMsgBox(
      {
        title: opts.title,
        content: opts.content,
        contentHtml: opts.contentHtml,
        positiveText: opts.positiveText || '确认',
        negativeText: opts.negativeText || '取消',
        onPositive() {
          resolve(true)
        },
        onNegative() {
          resolve(false)
        }
      },
      'warn'
    )
  })
}
